package com.itheima.rpc.client.discovery.zk;

import com.itheima.rpc.client.cache.local.DefaultServiceProviderCache;
import com.itheima.rpc.client.discovery.RpcServiceDiscovery;
import com.itheima.rpc.provider.ServiceProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class ZkServiceDiscovery implements RpcServiceDiscovery {

    @Resource
    private ClientZKit clientZKit;

    @Resource
    private DefaultServiceProviderCache serviceProviderCache;

    @Override
    public void serviceDiscovery() {
        //获取所有的服务名
        List<String> serviceList = clientZKit.getServiceList();

        if (ObjectUtils.isEmpty(serviceList)) {
            log.info("未拉取到可用的服务");
            return;
        }
        for (String serviceName : serviceList) {
            //拉取服务名下面所有的提供者ip:端口号
            List<ServiceProvider> providers = clientZKit.getServiceInfos(serviceName);
            log.info("服务名：{}，服务提供者：{}", serviceName, providers);
            //放入缓存
            serviceProviderCache.put(serviceName, providers);
            //监听服务名节点变化
            clientZKit.subscribeZKEvent(serviceName);
        }
    }
}
